package se.jayway.millionaire.client;

import java.io.File;

import se.jayway.millionaire.internal.game.SimpleGame;
import se.jayway.millionaire.internal.repository.FileSolutionRepository;
import se.jayway.millionaire.model.game.Game;
import se.jayway.millionaire.model.game.Player;
import se.jayway.millionaire.model.repository.SolutionRepository;

public class Main {
	public static void main(String[] args) {
		Arguments arguments = Arguments.parse(args);

		// Start the game
		Game game = new SimpleGame(
				getSolutionRepository(
						arguments.getDatabaseFile()));
		game.start();

		// Simulate some players
		for (int i = 0; i < arguments.getNumberOfPlayers(); i++) {
			Player player = new RandomPlayer("Player" + i);
			game.newGameSession(player);
		}
	}

	private static SolutionRepository getSolutionRepository(File file) {
		FileSolutionRepository repository = new FileSolutionRepository(file);
		repository.populate();
		return repository;
	}
	
	static class Arguments {
		private File file;
		private final int numberOfPlayers;

		private Arguments(File file, int numberOfPlayers) {
			this.file = file;
			this.numberOfPlayers = numberOfPlayers;
		}

		public File getDatabaseFile() {
			return file;
		}
		
		public int getNumberOfPlayers() {
			return numberOfPlayers;
		}
		
		public static Arguments parse(String[] args) {
			if (args.length < 2) {
				throw new IllegalArgumentException("Missing database-file number-of-players arguments");
			}
			
			return new Arguments(parseFile(args[0]), parseNumberOfPlayers(args[1]));
		}

		private static int parseNumberOfPlayers(String arg) {
			try {
				return Integer.parseInt(arg);
			} catch (NumberFormatException e) {
				throw new IllegalArgumentException("Argument " + arg + " is not a number", e);
			}
		}

		private static File parseFile(String path) {
			File file = new File(path);
			if (!file.exists()) {
				throw new IllegalArgumentException("File " + path + " does not exist");
			}
			
			if (!file.isFile()) {
				throw new IllegalArgumentException("File " + path + " is not a file");
			}

			return file;
		}
	}
}
